package com.gtenacg.cartoonservice.util;

import com.gtenacg.cartoonservice.compent.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.MacAlgorithm;
import io.jsonwebtoken.security.SignatureException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class JwtUtil {
    // 签名算法
    private static final MacAlgorithm ALGORITHM = Jwts.SIG.HS256;

    // 配置
    final JwtProperties jwtProperties;

    // 密钥
    private static SecretKey secretKey = null;

    public static final String Default_Subject_Key = "admin";

    public String getToken(Map<String, Object> map) {
        return getToken(map, Default_Subject_Key);
    }
    public String getToken(Map<String, Object> map, String subjectKey) {
        Date now = new Date();
        Date expireDate = new Date(now.getTime() + (60 * 1000 * jwtProperties.getExpire()));

        return Jwts.builder()
                .signWith(getSecretKey(), ALGORITHM)
                .claims(map)
                .subject(jwtProperties.getSubjectMap().get(subjectKey)) // 令牌使用场景
                .issuer(jwtProperties.getIssuer()) // 签发者
                .issuedAt(now) // 签发时间
                .expiration(expireDate) // 过期时间
                .compact();
    }


    /**
     * // JWT签名无效
     * SignatureException
     * <p>
     * // JWT格式错误
     * MalformedJwtException
     * <p>
     * // JWT已过期
     * ExpiredJwtException
     * <p>
     * // 不支持的JWT
     * UnsupportedJwtException
     * <p>
     * // JWT字符串为空或其他参数无效
     * IllegalArgumentException
     */

    public Claims parseToken(String token) throws SignatureException {
        return Jwts.parser()
                .verifyWith(getSecretKey())
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }

    // 获取密钥
    private SecretKey getSecretKey() {
        if (secretKey == null) {
            byte[] bytes = jwtProperties.getPwd().getBytes();
            if (bytes.length != 32) {
                bytes = Arrays.copyOf(bytes, 32);
            }
            secretKey = Keys.hmacShaKeyFor(bytes);
        }
        return secretKey;
    }
}
